import useUserStore from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'
import useDictStore from '@/store/modules/dict';
import router from '..'
import UserService from '@/service/system/user';
import { UserState } from '@/store/types'

const whiteRoutes: string[] = ['/login', '/404', '/403', '/500']

function usePermissionGuard() {
  router.beforeEach(async (to) => {
    if (whiteRoutes.includes(to.path)) {
      return true
    }
    const userStore = useUserStore()
    if (userStore.isTokenExpire()) {
      // 清空用户所有信息
      userStore.logout()
      return {
        path: '/login',
        query: { redirect: to.fullPath },
      }
    }
    // 如果用户名为空，则获取当前用户信息，保存到本地
    if (!userStore.account) {
      // 获取用户信息，保存到pinia中
      UserService.getUserInfo().then((res: any) => {
        const userInfo: UserState = {
          account: res.data.account,
          areaId: res.data.areaId,
          company: res.data.company,
          descName: res.data.descName,
          description: res.data.description,
          mobile: res.data.mobile,
          real_name: res.data.real_name,
        }
        userStore.saveUser(userInfo)
      })
    } else {
      // 如果保存过了用户信息，我们每次都检查token是否过期
      const res = await UserService.checkToken()
      if (res.code == 401) {
        // 清空用户所有信息
        userStore.logout()
        return {
          path: '/login',
          query: { redirect: to.fullPath },
        }
      }
    }
    const dictStore = useDictStore()
    // 如果字典为空，我们就获取字典
    if (dictStore.isEmptyDict()) {
      dictStore.getDicts()
    }
    const permissionStore = usePermissionStore()
    const isEmptyRoute = permissionStore.isEmptyPermissionRoute()
    if (isEmptyRoute) {
      await permissionStore.initPermissionRoute()
      return { ...to, replace: true }
    }
    return true
  })
}

export default usePermissionGuard
